<script lang="ts">
  import { WOED_TABBAR_PAGE } from '@/constants/path';
  import { useGoEasyListen, useLoadConversations } from '@/hooks/go-easy.hooks';
  import { onShow } from '@/hooks/uniapp-composition-hooks';
  import { computed, defineComponent, ref } from '@vue/composition-api';
  import {
    getDictionaryWords,
    DictionaryWords,
    answerMannyProblem,
    getRanDataLimit,
    answerOneProblem,
    collectionWord,
    getDictionaryList,
    Dictionary
  } from '@/api/dictionary';
  import { DOUBLE_STATUS } from '@/enum/common';
  import { Message } from '@/libs';
  import { ROUTER_PATHS, useRouter } from '@/constants/router';

  export default defineComponent({
    setup() {
      try {
        useGoEasyListen();
      } catch (error) {
        console.log(error);
      }
      const router = useRouter();

      const dictionaryListShow = ref(false);
      const dictionaryList = ref<Dictionary[]>([]);
      const dictionarySelectItem = ref('CTE-4');

      function loadDictionary() {
        return getDictionaryList().then((res) => {
          dictionaryList.value = res.data;
          dictionarySelectItem.value = dictionaryList.value[0].dictionaryName;
          dictionaryId.value = dictionaryList.value[0].id;
        });
      }
      loadDictionary();
      function showDictionarySelect() {
        dictionaryListShow.value = true;
      }

      const playStyleAnimation = 'play 1.6s linear';
      const translateShowStatus = ref(true);

      const playStyle = ref({
        animation: ''
      });
      const wordCardStyle = ref<{
        position: string;
        width: string;
        height: string;
        zIndex: number;
        top: number;
        left: number;
        marginTop: number;
      } | null>(null);

      const dictionaryWords = ref<DictionaryWords>({
        id: 0,
        collectionStatus: DOUBLE_STATUS.UN_NORMAL,
        dictionaryId: 0,
        wordContent: '',
        wordPronunciation: '',
        wordTranslate: ''
      });
      const dictionaryId = ref(1);
      // 随机答案数组
      const randAnswerData = ref<string[]>([]);

      function changeWordCardStyle() {
        if (!wordCardStyle.value) {
          wordCardStyle.value = {
            position: 'fixed',
            width: '100vw',
            height: '100vh',
            zIndex: 100,
            top: 0,
            left: 0,
            marginTop: 0
          };
        } else {
          wordCardStyle.value = null;
        }
      }

      const innerAudioContext = uni.createInnerAudioContext();
      function playWordSound() {
        playStyle.value.animation = playStyleAnimation;
        innerAudioContext.src = `http://dict.youdao.com/dictvoice?type=0&audio=${dictionaryWords.value.wordContent}`;
        innerAudioContext.play();
        setTimeout(() => {
          playStyle.value.animation = '';
        }, 1600);
      }

      function changeTranslateShowStatus() {
        translateShowStatus.value = !translateShowStatus.value;
      }

      function shuffle<AItem = any>(arr: Array<AItem>) {
        var l = arr.length;
        var index, temp;
        while (l > 0) {
          index = Math.floor(Math.random() * l);
          temp = arr[l - 1];
          arr[l - 1] = arr[index];
          arr[index] = temp;
          l--;
        }
        return arr;
      }

      function loadWords() {
        console.log('dictionaryId.value', dictionaryId.value);

        return getDictionaryWords(dictionaryId.value).then((res) => {
          dictionaryWords.value = res.data.list[0];
          return getRanDataLimit({
            limit: 3,
            id: dictionaryWords.value.id
          }).then((res) => {
            const result = res.data.map((item) => {
              return item.wordTranslate;
            });
            result.push(dictionaryWords.value.wordTranslate);
            randAnswerData.value = shuffle(result);
          });
        });
      }

      loadWords();

      function startTest() {
        changeWordCardStyle();
      }

      function nextWord() {
        answerMannyProblem({
          dictionaryId: dictionaryWords.value.dictionaryId,
          wordId: dictionaryWords.value.id,
          answer: dictionaryWords.value.wordTranslate
        })
          .then((res) => {
            console.log(res);
            loadWords();
          })
          .then((err) => {
            console.log(err);
          });
      }

      function toCollectionWords() {
        collectionWord({
          wordId: dictionaryWords.value.id,
          dictionaryId: dictionaryWords.value.dictionaryId
        }).then((res) => {
          dictionaryWords.value.collectionStatus = res.data.status;
        });
      }

      function anserSelect(answer: string) {
        answerOneProblem({
          wordId: dictionaryWords.value.id,
          dictionaryId: dictionaryWords.value.dictionaryId,
          answer
        })
          .then(() => {
            Message.success('回答正确,您可以继续下一个啦！');
            changeWordCardStyle();
          })
          .catch((err) => {
            console.log(err);
          });
      }

      const collectionStatusImagePath = computed(() => {
        if (dictionaryWords.value.collectionStatus === DOUBLE_STATUS.NORMAL) {
          return WOED_TABBAR_PAGE.COLLECTIONED;
        } else {
          return WOED_TABBAR_PAGE.COLLECTION;
        }
      });

      function selectDictionary(list: { label: string; value: number }[]) {
        const item = list[0];
        console.log('value', item);
        dictionarySelectItem.value = item.label;
        dictionaryId.value = item.value;
        loadWords();
      }

      function toPage() {
        router.navigateTo({
          url: ROUTER_PATHS.WORD_OTHER
        });
      }

      onShow(() => {
        useLoadConversations();
      });

      return {
        dictionarySelectItem,
        dictionaryId,
        dictionaryListShow,
        dictionaryWords,
        WOED_TABBAR_PAGE,
        playStyle,
        translateShowStatus,
        wordCardStyle,
        randAnswerData,
        collectionStatusImagePath,
        dictionaryList,
        showDictionarySelect,
        loadDictionary,
        selectDictionary,
        anserSelect,
        startTest,
        nextWord,
        playWordSound,
        changeTranslateShowStatus,
        changeWordCardStyle,
        toCollectionWords,
        toPage
      };
    }
  });
</script>

<template>
  <view class="word">
    <view class="tab">
      <view class="tab-left" @click.stop="showDictionarySelect">
        <image class="tab-left-book" :src="WOED_TABBAR_PAGE.BOOK" />
        <view class="tab-left-dictionary"> {{ dictionarySelectItem }} </view>
      </view>
      <image class="tab-history" :src="WOED_TABBAR_PAGE.HISTORY" @click.stop="toPage" />
    </view>
    <view class="content">
      <view class="word-card" :style="[wordCardStyle]" @click.stop="() => {}" @touchmove.stop.prevent="() => {}">
        <view class="word-card-header">
          <view class="word-card-header-listen-body">
            <view class="word-card-header-close" v-if="wordCardStyle" @click.stop="changeWordCardStyle">X</view>
            <image class="word-card-header-listen" :src="WOED_TABBAR_PAGE.LISTEN" />
          </view>
          <image @click.stop="toCollectionWords" class="word-card-header-collection" :src="collectionStatusImagePath" />
        </view>
        <view class="word-card-content">
          <view class="content-word">{{ dictionaryWords.wordContent }}</view>
          <view class="content-tanslate">
            <template v-if="!wordCardStyle">
              <view
                v-if="!translateShowStatus"
                class="content-tanslate-message"
                @click.stop="changeTranslateShowStatus"
              >
                <view class="pronunciation">
                  {{ dictionaryWords.wordPronunciation }}
                </view>
                <text class="translate">
                  {{ dictionaryWords.wordTranslate }}
                </text>
              </view>
              <view class="content-tanslat-cover" v-if="translateShowStatus" @click.stop="changeTranslateShowStatus">
                点我显示翻译
              </view>
            </template>
            <template v-if="wordCardStyle">
              <view class="content-tanslate-options">
                <view
                  class="content-tanslate-options-item"
                  v-for="(item, index) in randAnswerData"
                  :key="index"
                  @click.stop="anserSelect(item)"
                >
                  <text>{{ item }}</text>
                </view>
              </view>
            </template>
          </view>
          <view class="content-play">
            <view class="content-play-button">
              <image :src="WOED_TABBAR_PAGE.PLAY" :style="[playStyle]" @click.stop="playWordSound" />
            </view>
          </view>
        </view>
      </view>
      <view class="content-bottom">
        <button class="bottom-test-button" @click.stop="startTest">开始测试</button>
        <button class="bottom-test-button" @click.stop="nextWord">下一个</button>
      </view>
    </view>
    <u-select
      v-model="dictionaryListShow"
      mode="single-column"
      :default-value="dictionaryId"
      :list="dictionaryList"
      value-name="id"
      label-name="dictionaryName"
      @confirm="selectDictionary"
    ></u-select>
  </view>
</template>

<style>
  @keyframes play {
    0% {
      opacity: 0;
    }
    100% {
      transform: 1.1;
    }
  }
</style>

<style lang="scss" scoped>
  .word {
    height: 100vh;
    padding: 10rpx 52rpx 0 52rpx;
    background-color: #f8f8f8;

    .tab {
      display: flex;
      justify-content: space-between;
      align-items: center;

      &-left {
        display: flex;
        align-items: center;

        &-book {
          width: 48rpx;
          height: 48rpx;
        }

        &-dictionary {
          margin-left: 15rpx;
        }
      }

      &-history {
        width: 48rpx;
        height: 48rpx;
      }
    }

    .content {
      .word-card {
        height: 75vh;
        margin-top: 5vw;
        border-radius: 2vw;
        background-color: #fff;
        position: relative;
        box-shadow: 2rpx 2rpx 25rpx #dddddd;
        transition: all 0.5s;
        display: flex;
        flex-direction: column;
        padding: 10rpx 30rpx 0 30rpx;

        &-header {
          height: 60rpx;
          position: relative;
          display: flex;
          justify-content: space-between;
          align-items: center;

          &-close {
            width: 32rpx;
            height: 32rpx;
            margin-right: 10rpx;
          }

          &-listen-body {
            display: flex;
            align-items: center;
          }

          &-listen {
            width: 32rpx;
            height: 32rpx;
          }

          &-collection {
            width: 32rpx;
            height: 32rpx;
          }
        }

        &-content {
          flex: 1;
          display: flex;
          flex-direction: column;

          .content-word {
            font-size: 44rpx;
            color: #1a1a1a;
            font-weight: bold;
            text-align: center;
          }

          .content-tanslate {
            flex: 1;
            position: relative;

            &-options {
              width: 100%;
              height: 100%;
              display: flex;
              flex-direction: column;
              justify-content: center;

              &-item {
                width: 100%;
                height: 12vw;
                margin-bottom: 4vw;
                background-color: #fff;
                border-radius: 5px;
                box-shadow: 1px 1px 10px #dadada;
                cursor: pointer;
                position: relative;
                transition: 0.3s all;
                font-size: 3.5vw;
                color: #383838;
                text-align: center;
                line-height: 12vw;
                overflow: hidden;
                &:active {
                  background-color: darkseagreen;
                }
              }
            }

            &-message {
              width: 100%;
              height: 100%;
              padding: 20rpx;
              display: flex;
              justify-content: center;
              align-items: center;
              flex-direction: column;
              .pronunciation {
                text-align: center;
              }

              .translate {
                margin-top: 20rpx;
                text-align: center;
              }
            }

            .content-tanslat-cover {
              position: absolute;
              left: 0;
              top: 0;
              right: 0;
              bottom: 0;
              display: flex;
              justify-content: center;
              align-items: center;
            }
          }

          .content-play {
            height: 80rpx;

            &-button {
              margin: 0 auto;
              width: 56rpx;
              height: 56rpx;
              border: 2rpx solid #515151;
              border-radius: 50%;
              display: flex;
              align-items: center;
              justify-content: center;

              image {
                width: 48rpx;
                height: 48rpx;
                opacity: 1.1;
              }
            }
          }
        }
      }

      .content-bottom {
        margin-top: 40rpx;
        display: flex;
        justify-content: space-between;
        .bottom-test-button {
          width: 45%;
          background-color: #fff;
          margin-bottom: 2vw;
          font-size: 4vw;
          color: #383838;
          box-shadow: 2rpx 2rpx 25rpx #ececec;
        }
      }
    }
  }
</style>
